document.addEventListener('DOMContentLoaded', () => {
    // 拼图配置 - 默认3x3
    let PUZZLE_SIZE = 3;
    let PIECE_COUNT = PUZZLE_SIZE * PUZZLE_SIZE;

    // 游戏状态
    let pieces = [];
    let placedPieces = 0;
    let correctPieces = 0;
    let timer = null;
    let seconds = 0;
    let isPlaying = false;
    let imageLoaded = false;
    let uploadedImageData = null;
    let selectedPieceIndex = null; // 选中的拼图块索引
    let audioContext = null; // 音频上下文

    // DOM 元素
    const piecesContainer = document.getElementById('pieces-container');
    const puzzleBoard = document.getElementById('puzzle-board');
    const timerDisplay = document.getElementById('timer');
    const placedCountDisplay = document.getElementById('placed-count');
    const totalPiecesDisplay = document.getElementById('total-pieces');
    const correctCountDisplay = document.getElementById('correct-count');
    const correctTotalDisplay = document.getElementById('correct-total');
    const resetButton = document.getElementById('reset-btn');
    const hintButton = document.getElementById('hint-btn');
    const winModal = document.getElementById('win-modal');
    const finalTimeDisplay = document.getElementById('final-time');
    const finalPiecesDisplay = document.getElementById('final-pieces');
    const playAgainButton = document.getElementById('play-again');
    const puzzleSizeSelect = document.getElementById('puzzle-size');
    const viewOriginalButton = document.getElementById('view-original-btn');
    const uploadImageButton = document.getElementById('upload-image-btn');
    const imageUploadInput = document.getElementById('image-upload');
    const imageModal = document.getElementById('image-modal');
    const closeImageButton = document.getElementById('close-image');

    // 原图查看功能
    viewOriginalButton.addEventListener('click', () => {
        imageModal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    });

    // 上传图片功能
    uploadImageButton.addEventListener('click', () => {
        imageUploadInput.click();
    });

    imageUploadInput.addEventListener('change', (e) => {
        if (e.target.files && e.target.files[0]) {
            const file = e.target.files[0];
            const reader = new FileReader();

            reader.onload = function(event) {
                const img = new Image();
                img.src = event.target.result;

                img.onload = function() {
                    // 创建一个canvas来裁剪图片
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    // 计算裁剪区域，使其居中且尽可能小
                    let cropSize = Math.min(img.width, img.height);
                    let cropX = (img.width - cropSize) / 2;
                    let cropY = (img.height - cropSize) / 2;
                    
                    // 设置canvas大小
                    canvas.width = cropSize;
                    canvas.height = cropSize;
                    
                    // 绘制裁剪后的图片
                    ctx.drawImage(img, cropX, cropY, cropSize, cropSize, 0, 0, cropSize, cropSize);
                    
                    // 获取裁剪后的图片数据
                    const croppedImageData = canvas.toDataURL('image/png');
                    
                    // 更新模态框中的图片
                    const modalImage = document.querySelector('#image-modal img');
                    modalImage.src = croppedImageData;
                    
                    // 更新拼图区域使用的图片
                    uploadedImageData = croppedImageData;
                    
                    // 重新初始化游戏
                    initGame();
                };
            };

            reader.readAsDataURL(file);
        }
    });

    closeImageButton.addEventListener('click', () => {
        imageModal.classList.add('hidden');
        document.body.style.overflow = '';
    });

    imageModal.addEventListener('click', (e) => {
        if (e.target === imageModal) {
            imageModal.classList.add('hidden');
            document.body.style.overflow = '';
        }
    });

    // 初始化游戏
    function initGame() {
        PUZZLE_SIZE = parseInt(puzzleSizeSelect.value);
        PIECE_COUNT = PUZZLE_SIZE * PUZZLE_SIZE;

        // 更新显示
        totalPiecesDisplay.textContent = PIECE_COUNT;
        correctTotalDisplay.textContent = PIECE_COUNT;

        // 重置游戏状态
        placedPieces = 0;
        correctPieces = 0;
        seconds = 0;
        isPlaying = false;
        selectedPieceIndex = null; // 重置选中的拼图块
        placedCountDisplay.textContent = `0/${PIECE_COUNT}`;
        correctCountDisplay.textContent = `0/${PIECE_COUNT}`;
        timerDisplay.textContent = '00:00';

        if (timer) {
            clearInterval(timer);
            timer = null;
        }

        // 清空容器
        piecesContainer.innerHTML = '';
        puzzleBoard.innerHTML = '';
        winModal.classList.add('hidden');
        imageModal.classList.add('hidden');
        document.body.style.overflow = '';

        // 创建拼图块数据
        pieces = Array.from({ length: PIECE_COUNT }, (_, i) => i);

        // 确保拼图块容器是正方形（关键修复）
        setPiecesContainerAspectRatio();

        // 初始化拼图块容器为网格结构
        initPiecesContainerGrid();

        // 初始化音频上下文
        initAudio();

        // 加载图片并创建拼图
        loadImageAndCreatePuzzle();
    }

    // 关键修复：确保拼图块容器保持正方形比例
    function setPiecesContainerAspectRatio() {
        // 移除旧的样式和事件监听
        piecesContainer.style.height = '';
        window.removeEventListener('resize', updatePiecesContainerHeight);

        // 设置容器为相对定位
        piecesContainer.style.position = 'relative';
        piecesContainer.style.width = '100%';

        // 初始化高度并添加窗口大小改变监听
        updatePiecesContainerHeight();
        window.addEventListener('resize', updatePiecesContainerHeight);
    }

    // 根据宽度更新高度，保持1:1比例
    function updatePiecesContainerHeight() {
        const width = piecesContainer.offsetWidth;
        piecesContainer.style.height = `${width}px`;
    }

    // 初始化拼图块容器为网格结构
    function initPiecesContainerGrid() {
        // 计算每个格子的大小（百分比）
        const cellSize = 100 / PUZZLE_SIZE;

        // 创建与拼图区域相同数量的格子
        for (let row = 0; row < PUZZLE_SIZE; row++) {
            for (let col = 0; col < PUZZLE_SIZE; col++) {
                const cell = document.createElement('div');
                const cellIndex = row * PUZZLE_SIZE + col;

                // 设置格子样式，与拼图区域的槽位大小一致
                cell.className = 'piece-cell absolute border border-slate-100 bg-slate-50/30 box-sizing';
                cell.style.width = `${cellSize}%`;
                cell.style.height = `${cellSize}%`;
                cell.style.left = `${col * cellSize}%`;
                cell.style.top = `${row * cellSize}%`;
                cell.dataset.index = cellIndex;
                cell.dataset.isEmpty = 'true'; // 标记格子是否为空

                piecesContainer.appendChild(cell);
            }
        }
    }

    // 加载图片并创建拼图
    function loadImageAndCreatePuzzle() {
        const img = new Image();
        
        // 如果有上传的图片数据，使用它；否则使用默认图片
        if (uploadedImageData) {
            img.src = uploadedImageData;
        } else {
            img.src = 'picture.png';
        }

        img.onload = function() {
            imageLoaded = true;
            createPuzzleSlots(img);
            createPuzzlePieces(img);
        };

        img.onerror = function() {
            console.error('无法加载图片');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'absolute inset-0 flex items-center justify-center bg-red-50 p-4';
            errorDiv.innerHTML = `
                    <div class="text-center">
                        <i class="fa fa-exclamation-triangle text-red-500 text-4xl mb-2"></i>
                        <p class="text-red-600">无法加载图片</p>
                        <p class="text-slate-500 text-sm mt-1">请确保选择了有效的图片文件</p>
                    </div>
                `;
            puzzleBoard.appendChild(errorDiv);
        };
    }

    // 创建拼图槽位
    function createPuzzleSlots(img) {
        const slotSize = 100 / PUZZLE_SIZE; // 百分比

        for (let row = 0; row < PUZZLE_SIZE; row++) {
            for (let col = 0; col < PUZZLE_SIZE; col++) {
                const slot = document.createElement('div');
                const index = row * PUZZLE_SIZE + col;

                slot.className = 'puzzle-slot absolute border border-slate-200 box-sizing';
                slot.style.width = `${slotSize}%`;
                slot.style.height = `${slotSize}%`;
                slot.style.left = `${col * slotSize}%`;
                slot.style.top = `${row * slotSize}%`;
                slot.dataset.index = index;
                slot.dataset.occupied = 'false';
                slot.dataset.pieceIndex = '-1';

                // 添加点击事件
                slot.addEventListener('click', handleSlotClick);

                puzzleBoard.appendChild(slot);
            }
        }
    }

    // 创建拼图块
    function createPuzzlePieces(img) {
        const piecesArray = [...pieces];
        const pieceCells = piecesContainer.querySelectorAll('.piece-cell');

        // 打乱拼图块顺序
        shuffleArray(piecesArray);

        piecesArray.forEach((index, i) => {
            const row = Math.floor(index / PUZZLE_SIZE);
            const col = index % PUZZLE_SIZE;

            // 创建拼图块
            const piece = document.createElement('div');
            piece.className = 'puzzle-piece puzzle-shadow rounded-sm overflow-hidden relative border border-white';
            piece.style.width = '100%';
            piece.style.height = '100%';
            piece.draggable = false; // 禁用拖拽
            piece.dataset.index = index;

            // 添加双击事件
            piece.addEventListener('dblclick', function() {
                const slot = this.parentElement;
                if (slot && slot.classList.contains('puzzle-slot')) {
                    returnPieceToPool(this, slot);
                }
            });

            // 添加点击事件
            piece.addEventListener('click', handlePieceClick);

            // 设置背景图
            if (uploadedImageData) {
                piece.style.backgroundImage = `url(${uploadedImageData})`;
            } else {
                piece.style.backgroundImage = `url('picture.png')`;
            }
            piece.style.backgroundSize = `${PUZZLE_SIZE * 100}% ${PUZZLE_SIZE * 100}%`;
            piece.style.backgroundPosition = `-${col * 100}% -${row * 100}%`;

            // 将拼图块放入对应的格子中
            if (pieceCells[i]) {
                pieceCells[i].appendChild(piece);
                pieceCells[i].dataset.isEmpty = 'false';
            }
        });
    }

    // 将拼图块返回闲置区
    function returnPieceToPool(piece, slot) {
        const pieceIndex = piece.dataset.index;
        const slotIndex = slot.dataset.index;

        // 添加双击动画效果
        piece.classList.add('double-click-effect');
        setTimeout(() => {
            piece.classList.remove('double-click-effect');
        }, 500);

        // 检查该拼图块是否放置正确
        if (pieceIndex === slotIndex) {
            correctPieces--;
            correctCountDisplay.textContent = `${correctPieces}/${PIECE_COUNT}`;
        }

        // 恢复拼图块属性
        piece.draggable = true;
        piece.classList.add('puzzle-hover', 'cursor-grab', 'active:cursor-grabbing');
        piece.classList.remove('correct-position', 'wrong-position');

        // 重置拼图块样式
        piece.style.position = 'static';
        piece.style.width = '100%';
        piece.style.height = '100%';
        piece.style.paddingBottom = '0';

        // 查找一个空的格子
        const allCells = piecesContainer.querySelectorAll('.piece-cell');
        let foundEmptyCell = false;
        
        for (let i = 0; i < allCells.length; i++) {
            const cell = allCells[i];
            // 检查格子是否为空（没有子元素）
            if (cell.children.length === 0) {
                cell.appendChild(piece);
                cell.dataset.isEmpty = 'false';
                foundEmptyCell = true;
                break;
            }
        }
        
        // 如果没有找到空格子，降级处理
        if (!foundEmptyCell) {
            const pieceContainer = document.createElement('div');
            pieceContainer.className = 'puzzle-hover cursor-grab active:cursor-grabbing';
            pieceContainer.appendChild(piece);
            piecesContainer.appendChild(pieceContainer);
        }

        // 重置槽位状态
        slot.dataset.occupied = 'false';
        slot.dataset.pieceIndex = '-1';
        slot.innerHTML = '';

        // 更新计数
        placedPieces--;
        placedCountDisplay.textContent = `${placedPieces}/${PIECE_COUNT}`;

        // 播放放置音效
        playPlaceSound();
    }

    // 打乱数组顺序
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }

    // 点击拼图块事件处理函数
    function handlePieceClick() {
        // 移除之前选中拼图块的样式
        document.querySelectorAll('.puzzle-piece').forEach(piece => {
            piece.classList.remove('selected');
        });

        // 添加选中样式
        this.classList.add('selected');
        
        // 保存选中的拼图块索引
        selectedPieceIndex = this.dataset.index;
        
        // 开始计时
        if (!isPlaying) {
            isPlaying = true;
            timer = setInterval(updateTimer, 1000);
        }
    }

    // 点击拼图槽位事件处理函数
    function handleSlotClick() {
        // 如果没有选中的拼图块，直接返回
        if (selectedPieceIndex === null) return;
        
        // 如果槽位已被占用，直接返回
        if (this.dataset.occupied === 'true') return;
        
        const targetSlotIndex = this.dataset.index;
        
        // 获取选中的拼图块
        const piece = document.querySelector(`.puzzle-piece[data-index="${selectedPieceIndex}"]`);
        if (piece) {
            const originalParent = piece.parentNode;
            let wasInSlot = false;
            let originalSlotIndex = -1;

            // 如果拼图块原来在槽位中
            if (originalParent && originalParent.classList.contains('puzzle-slot')) {
                wasInSlot = true;
                originalSlotIndex = originalParent.dataset.index;

                originalParent.dataset.occupied = 'false';
                originalParent.dataset.pieceIndex = '-1';

                if (selectedPieceIndex === originalSlotIndex) {
                    correctPieces--;
                }
            }

            // 从原位置移除拼图块
            if (originalParent) {
                originalParent.removeChild(piece);
            }

            // 更新拼图块样式
            piece.classList.remove('cursor-grab', 'active:cursor-grabbing', 'puzzle-hover', 'selected');

            // 将拼图块添加到目标槽位
            this.appendChild(piece);
            piece.style.position = 'absolute';
            piece.style.top = '0';
            piece.style.left = '0';
            piece.style.width = '100%';
            piece.style.height = '100%';
            piece.style.paddingBottom = '0';

            // 更新槽位状态
            this.dataset.occupied = 'true';
            this.dataset.pieceIndex = selectedPieceIndex;

            // 更新拼图块位置状态
            piece.classList.remove('correct-position', 'wrong-position');
            if (selectedPieceIndex === targetSlotIndex) {
                piece.classList.add('correct-position');
                correctPieces++;
            } else {
                piece.classList.add('wrong-position');
            }

            // 更新计数
            if (!wasInSlot) {
                placedPieces++;
            }
            placedCountDisplay.textContent = `${placedPieces}/${PIECE_COUNT}`;
            correctCountDisplay.textContent = `${correctPieces}/${PIECE_COUNT}`;

            // 播放放置音效
            playPlaceSound();

            // 检查是否完成拼图
            if (correctPieces === PIECE_COUNT) {
                completePuzzle();
            }
            
            // 重置选中的拼图块
            selectedPieceIndex = null;
        }
    }

    // 更新计时器
    function updateTimer() {
        seconds++;
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    // 播放胜利音效
    function playWinSound() {
        if (!audioContext) return;

        // 创建一个更快的胜利音效序列
        const notes = [
            { frequency: 523.25, duration: 0.15, delay: 0 },    // C5
            { frequency: 659.25, duration: 0.15, delay: 0.15 },  // E5
            { frequency: 783.99, duration: 0.15, delay: 0.3 },   // G5
            { frequency: 1046.5, duration: 0.3, delay: 0.45 }    // C6 (高八度)
        ];

        const now = audioContext.currentTime;
        const masterGain = audioContext.createGain();
        masterGain.connect(audioContext.destination);
        masterGain.gain.value = 0.25; // 适中的音量

        notes.forEach(note => {
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(masterGain);
            
            oscillator.type = 'sine';
            oscillator.frequency.value = note.frequency;
            
            // 设置更有趣的音量包络
            gainNode.gain.setValueAtTime(0, now + note.delay);
            gainNode.gain.linearRampToValueAtTime(0.7, now + note.delay + 0.01);
            gainNode.gain.exponentialRampToValueAtTime(0.001, now + note.delay + note.duration);
            
            oscillator.start(now + note.delay);
            oscillator.stop(now + note.delay + note.duration);
        });
    }

    // 完成拼图
    function completePuzzle() {
        isPlaying = false;
        clearInterval(timer);

        finalTimeDisplay.textContent = timerDisplay.textContent;
        finalPiecesDisplay.textContent = PIECE_COUNT;
        winModal.classList.remove('hidden');

        // 播放胜利音效
        playWinSound();
    }

    // 初始化音频功能
    function initAudio() {
        // 创建音频上下文
        if (!audioContext) {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
        }
    }

    // 播放放置音效
    // 播放放置音效
    function playPlaceSound() {
        if (!audioContext) return;
    
        // 创建 oscillator（振荡器）和 gain node（增益节点）
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
    
        // 连接节点
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
    
        // 设置音调和音量（更高的音调，更适合儿童）
        oscillator.type = 'sine'; // 正弦波
        oscillator.frequency.value = 784.0; // G5 音符 (约 784 Hz)，比之前更高
        gainNode.gain.value = 0.2; // 稍微降低音量
    
        // 设置音效的持续时间（更短，更轻快）
        const now = audioContext.currentTime;
        oscillator.start(now);
        oscillator.stop(now + 0.05); // 0.05 秒后停止，比之前更短
    
        // 更快的音量渐变
        gainNode.gain.setValueAtTime(gainNode.gain.value, now);
        gainNode.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
    }

    // 提示功能
    function showHint() {
        // 如果游戏未开始，启动计时器
        if (!isPlaying && imageLoaded) {
            isPlaying = true;
            timer = setInterval(updateTimer, 1000);
        }
        
        if (!imageLoaded) return;

        // 查找所有还未正确放置的拼图块
        // 这些拼图块要么在闲置区（piece-cell中），要么在错误的槽位中
        const allPieces = document.querySelectorAll('.puzzle-piece');
        const unplacedPieces = Array.from(allPieces).filter(piece => {
            const pieceParent = piece.parentElement;
            // 如果拼图块在闲置区（piece-cell中），则认为未放置
            if (pieceParent && pieceParent.classList.contains('piece-cell')) {
                return true;
            }
            // 如果拼图块在槽位中，但位置不正确，则认为未放置
            if (pieceParent && pieceParent.classList.contains('puzzle-slot')) {
                const pieceIndex = piece.dataset.index;
                const slotIndex = pieceParent.dataset.index;
                return pieceIndex !== slotIndex;
            }
            return false;
        });

        if (unplacedPieces.length > 0) {
            const randomPiece = unplacedPieces[Math.floor(Math.random() * unplacedPieces.length)];
            const pieceIndex = randomPiece.dataset.index;

            const targetSlot = document.querySelector(`.puzzle-slot[data-index="${pieceIndex}"]`);
            if (targetSlot) {
                targetSlot.classList.add('slot-highlight');
                randomPiece.classList.add('ring-4', 'ring-accent', 'scale-110');

                setTimeout(() => {
                    targetSlot.classList.remove('slot-highlight');
                    randomPiece.classList.remove('ring-4', 'ring-accent', 'scale-110');
                }, 3000);
            }
        }
    }

    // 事件监听
    resetButton.addEventListener('click', initGame);
    playAgainButton.addEventListener('click', initGame);
    hintButton.addEventListener('click', showHint);
    puzzleSizeSelect.addEventListener('change', initGame);

    // 页面卸载前移除事件监听
    window.addEventListener('beforeunload', () => {
        window.removeEventListener('resize', updatePiecesContainerHeight);
    });

    // 初始化游戏
    initGame();
});
